<?php

namespace app\command\controller;

use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\model\Policy;
use app\common\model\StandardMoney;
use app\common\model\StandardRecord;
use fast\Http;
use fast\Rsa;
use LimitIterator;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;

class Task extends Controller
{
    public function getBills(){
        $days = 1;
        $date = date("Ymd",strtotime("-{$days} day"));
        $month = date("Ym",strtotime("-{$days} day"));
        $agentId = Constant::$agentId;
        $arr = [
            "agentId" => $agentId,
            "date" => $date,
        ];
        $url = "http://agentbill.jlpay.com/accountFile/download/{$agentId}/{$date}?sign_data=";
        $publicKey = Tools::getPemContent("public_key_pkcs8.pem");
        $privateKey = Tools::getPemContent("private_key_pkcs8.pem");
        $rsa = new Rsa($publicKey,$privateKey);
        $sign = $rsa->sign(json_encode($arr));
        $resource = Http::get($url . urlencode($sign));
        $error = json_decode($resource,true);
        if(is_array($error)){
            Libs::saveBillLog($date,$error['message']);
        }

        $path = ROOT_PATH."public/file/bill/".$month."/".$date."/";
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        $zipName = $path.$date.".zip";
        file_put_contents($zipName,$resource);

        $zip = zip_open($zipName);
        if ($zip) {
            while ($zip_entry = zip_read($zip)) {
                $entryName = zip_entry_name($zip_entry);
                $entryPath = $path . $entryName;

                if (zip_entry_open($zip, $zip_entry, "r")) {
                    $fp = fopen($entryPath, "w");
                    if ($fp) {
                        fwrite($fp, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                        fclose($fp);
                    }
                    zip_entry_close($zip_entry);
                }
            }
            zip_close($zip);

            self::readFile($path.$agentId."_".$date."_A01.txt",$date);
        } else {
            Libs::saveBillLog($date,"解压文件失败");
        }
    }

    private function readFile($path,$day){
        if(!is_file($path)){
            Libs::saveBillLog($day,"文件不存在！");
        }

        $file = fopen($path, "r");
        $list = [];

        while (!feof($file)) {
            $line = trim(fgets($file));
            $line = explode("|",$line);
            if(count($line) > 1){
                $standard = Libs::getStandardUnfinished($line[5]);
                if(!$standard){
                    $list[] = $line[5];
                    continue;
                }
                $now = time();
                if($standard && $line[8] > $standard->step && $now >= $standard->start_day && $now <= $standard->end_day){
                    switch ($line[8]){
                        case 1:
                            $money = 2000;
                            break;
                        case 2:
                            $money = 5000;
                            break;
                        case 3:
                            $money = 8000;
                            break;
                        case 4:
                            $money = 10000;
                            break;
                    }

                    $standard->accumulate_money = $money;
                    $standard->total_money = $money;
                    $standard->step = $line[8];
                    $standard->trading_time = strtotime($line[2]);
                }else{
                    if($standard && $now > $standard->end_day){
                        $standard->status = 2;
                        $standard->trading_time = strtotime($line[2]);
                    }
                }
                $standard->save();
            }
        }
        fclose($file);

        if(count($list) > 0){
            Libs::saveBillLog($day,implode(",",$list)."不存在达标记录！");
        }
    }

    public function standard()
    {
        if (Config::get("site.standard")) {
            $unStandardList = Libs::getUnStandardEquip();
            if(count($unStandardList) > 0){
                foreach ($unStandardList as $key => $val){
                    $equip = Lib::getEquip($val->sn);
                    $tableName = Constant::$productTable[$equip->product_id];
                    $orderInfo = Tools::getSatisfyOrder($val->sn, $val->require_money, $tableName,$val->start_day);

                    $tradingTime = 0;
                    $orderNum = "";
                    if (count($orderInfo) > 0) {
                        $tradingTime = $orderInfo[0]['trading_time'];
                        $orderNum = $orderInfo[0]['order_num'];
                    }

                    $level = Tools::getUserLevel($equip->main_id);
                    Db::startTrans();
                    try {
                        if(count($level) > 0){
                            $policyStandard = Libs::getPolicyByProductsLimit($equip->product_id,(int)$val->require_money);
                            $standardArr = [];
                            if(count($policyStandard) > 0){
                                foreach ($policyStandard as $keys => $value){
                                    $standardArr[$value->role] = $value->reward;
                                }
                            }
                            if(count($standardArr) > 0){
                                $startMoney = 0;
                                foreach ($level as $k => $v){
                                    $changeMoney = $standardArr[Constant::$levelAlia[$k]] - $startMoney;
                                    if($changeMoney > 0){
                                        Tools::saveMoney(2, $v, 3,$k, $changeMoney , $val->sn, $equip->product_id, "达标收益", ["table_name" => $tableName, "order_num" => $orderNum, "tran_time" => $tradingTime]);
                                    }
                                    $startMoney += $changeMoney;
                                }
                            }
                        }

                        $val->status = 1;
                        $val->trading_time = $tradingTime;
                        $val->save();
                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                    }
                }
            }
        }
    }

    public function flow()
    {
        //流量卡逻辑
        if (Config::get("site.flow")) {
            $unFlowList = Libs::getUnFlowEquip();
            if (count($unFlowList) > 0) {
                foreach ($unFlowList as $key => $val) {
                    Db::startTrans();
                    try {
                        $sn = $val->sn;
                        $equip = Lib::getEquip($sn);
                        $tableName = Constant::$productTable[$equip->product_id];
                        $level = Tools::getUserLevel($equip->main_id);
                        if(count($level) > 0){
                            $policyFlow = Libs::getPolicyFlowByProduct($equip->product_id);

                            if (!$policyFlow){
                                throw exception("未设置流量卡政策");
                            }

                            $policyFlow = $policyFlow->toArray();
                            $startMoney = 0;
                            foreach ($level as $k => $v){
                                $changeMoney = $policyFlow[Constant::$levelAlia[$k]] - $startMoney;
                                if($changeMoney > 0){
                                    Tools::saveMoney(2, $v, 2,$k, $changeMoney , $val->sn, $equip->product_id, "流量卡收益", ["table_name" => $tableName, "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                }
                                $startMoney += $changeMoney;
                            }
                        }

                        $val->status = 1;
                        $val->save();
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        file_put_contents("./trade_log/jl/flow_log.txt", "-------------------" . date("Y-m-d H:i:s") . "-----------------" . PHP_EOL, FILE_APPEND | LOCK_EX);
                        file_put_contents("./trade_log/jl/flow_log.txt", "SN:" . $val->sn . PHP_EOL, FILE_APPEND | LOCK_EX);
                        file_put_contents("./trade_log/jl/flow_log.txt", "error:" . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
                    }
                }
            }
        }
    }

    public function jl()
    {
        $baseUrl = "./trade_log/jl/";
        $fileName = "page.txt";

        if (!file_exists($baseUrl)) {
            mkdir($baseUrl, 0777, true);
        }

        if (!file_exists($baseUrl . $fileName)) {
            $pageInfo = ["page" => 1, "totalPage" => 0, "totalData" => 0];
            file_put_contents($baseUrl . $fileName, json_encode($pageInfo));
        }

        $pageInfo = json_decode(file_get_contents($baseUrl . $fileName), true);

        $list = Transaction::getJlDataList();

        $list = new \ArrayIterator($list);

        if ($list->count() == 0) {
            exit;
        }

        $page = $pageInfo['page'];
        $pageSize = 30;
        $currentPage = $page <= 1 ? 0 : $page - 1;
        $offset = $currentPage * $pageSize;
        $totalPage = ceil($list->count() / $pageSize);

        if ($page == $totalPage || $list->count() < $pageInfo['totalData']) {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        } else {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => $page + 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        }

        $pageData = new LimitIterator($list, $offset, $pageSize);
        foreach ($pageData as $key => $val) {
            $hour = date("H",time());
            if($hour < 4){//每天8点开始上分润
                break;
            }
            if ($val->sn) {
                $sn = $val->sn;

                $equip = Lib::getEquip($sn);
                $policy = Policy::where(["product_id"=>$equip->product_id])->find();

                if($equip && $policy){
                    Db::startTrans();
                    try {
                        $defaultRate = Libs::getEquipRate($sn,"D");
                        if($defaultRate){
//                            $userLevel = Libs::getUserLevel($equip->main_id);
                            $level = Tools::getUserLevel($equip->main_id);
                            $profit = Libs::getProfit($policy->id,$equip->product_id,$defaultRate->rate);

//                            $startProfit = 0;
                            foreach ($level as $k => $v) {
                                switch ($k){
                                    case "HX":
                                    case "JG":
                                        $calculateRate = (float)Constant::$profitStep;
                                        break;
                                    default:
                                        $calculateRate = $profit->profit_profit;
                                }

                                $profitMoney = Transaction::roundNumber($val->transaction_amount, $calculateRate);
//                                $diffMoney = $profitMoney - $startProfit;
                                if($profitMoney > 0){
                                    Tools::saveMoney(2, $v, 1, $k, $profitMoney, $sn, $equip->product_id, "分润收益", ["table_name" => "transaction_data_jl", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                }
//                                $startProfit = $profitMoney;
                            }
                        }

                        //调价收益
                        $adjustRate = Libs::getEquipRate($sn,"T");
                        if(count($adjustRate) > 0){
                            $level = Tools::getUserLevel($equip->main_id);
                            if(count($level) > 0) {
                                $policyAdjust = Libs::getPolicyAdjust($policy->id);

                                if (!$policyAdjust) {
                                    throw exception("未设置调价政策");
                                }

                                $policyAdjust = $policyAdjust->toArray();

                                $startRate = $defaultRate->rate;
                                foreach ($adjustRate as $keys => $value){//多次调价进行，每次调价单独进行收益计算
                                    $adjust = ($value->rate - $startRate) * 100;
                                    $changeMoney = Transaction::roundNumber($val->transaction_amount, $adjust);
                                    $startMoney = 0;
                                    foreach ($level as $k => $v) {//各级别角色收益分开计算
                                        $money = bcmul($changeMoney,$policyAdjust[Constant::$levelAlia[$k]] / 100,2);
                                        $finalMoney = $money - $startMoney;
                                        if ($finalMoney > 0) {
                                            Tools::saveMoney(2, $v, 9, $k, $finalMoney, $sn, $equip->product_id, "调价收益", ["table_name" => "transaction_data_jl", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                        }
                                        $startMoney = $money;
                                    }
                                    $startRate = $value->rate;
                                }
                            }
                        }

                        $val->handle_state = 2;
                        $val->handle_remark = "已处理";

                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        $val->handle_remark = $e->getMessage();
                    }
                }else{
                    $val->handle_state = 3;
                    $val->handle_remark = "设备或政策不存在";
                }

            } else {
                $val->handle_state = 3;
                $val->handle_remark = "订单无设备信息";
            }
            $val->save();
            sleep(1);
        }
    }

    public function ys()
    {
        $baseUrl = "./trade_log/ys/";
        $fileName = "page.txt";

        if (!file_exists($baseUrl)) {
            mkdir($baseUrl, 0777, true);
        }

        if (!file_exists($baseUrl . $fileName)) {
            $pageInfo = ["page" => 1, "totalPage" => 0, "totalData" => 0];
            file_put_contents($baseUrl . $fileName, json_encode($pageInfo));
        }

        $pageInfo = json_decode(file_get_contents($baseUrl . $fileName), true);

        $list = Transaction::getYsDataList();

        $list = new \ArrayIterator($list);

        if ($list->count() == 0) {
            exit;
        }

        $page = $pageInfo['page'];
        $pageSize = 30;
        $currentPage = $page <= 1 ? 0 : $page - 1;
        $offset = $currentPage * $pageSize;
        $totalPage = ceil($list->count() / $pageSize);

        if ($page == $totalPage || $list->count() < $pageInfo['totalData']) {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        } else {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => $page + 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        }

        $pageData = new LimitIterator($list, $offset, $pageSize);
        foreach ($pageData as $key => $val) {
            $hour = date("H",time());
            if($hour < 4){//每天8点开始上分润
                break;
            }
            if ($val->sn) {
                $sn = $val->sn;

                $equip = Lib::getEquip($sn);
                $policy = Policy::where(["product_id"=>$equip->product_id])->find();

                if($equip && $policy){
                    Db::startTrans();
                    try {
                        $defaultRate = Libs::getEquipRate($sn,"D");
                        if($defaultRate){
                            $level = Tools::getUserLevel($equip->main_id);
                            $profit = Libs::getProfit($policy->id,$equip->product_id,$defaultRate->rate);

//                            $startProfit = 0;
                            foreach ($level as $k => $v) {
                                switch ($k){
                                    case "HX":
                                    case "JG":
                                        $calculateRate = (float)Constant::$profitStep;
                                        break;
                                    default:
                                        $calculateRate = $profit->profit_profit;
                                }

                                $profitMoney = Transaction::roundNumber($val->transaction_amount, $calculateRate);
//                                $diffMoney = $profitMoney - $startProfit;
                                if($profitMoney > 0){
                                    Tools::saveMoney(2, $v, 1, $k, $profitMoney, $sn, $equip->product_id, "分润收益", ["table_name" => "transaction_data_ys", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                }
//                                $startProfit = $profitMoney;
                            }
                        }

                        //调价收益
                        $adjustRate = Libs::getEquipRate($sn,"T");
                        if(count($adjustRate) > 0){
                            $level = Tools::getUserLevel($equip->main_id);
                            if(count($level) > 0) {
                                $policyAdjust = Libs::getPolicyAdjust($policy->id);

                                if (!$policyAdjust) {
                                    throw exception("未设置调价政策");
                                }

                                $policyAdjust = $policyAdjust->toArray();

                                $startRate = $defaultRate->rate;
                                foreach ($adjustRate as $keys => $value){//多次调价进行，每次调价单独进行收益计算
                                    $adjust = ($value->rate - $startRate) * 100;
                                    $changeMoney = Transaction::roundNumber($val->transaction_amount, $adjust);
                                    $startMoney = 0;
                                    foreach ($level as $k => $v) {//各级别角色收益分开计算
                                        $money = bcmul($changeMoney,$policyAdjust[Constant::$levelAlia[$k]] / 100,2);
                                        $finalMoney = $money - $startMoney;
                                        if ($finalMoney > 0) {
                                            Tools::saveMoney(2, $v, 9, $k, $finalMoney, $sn, $equip->product_id, "调价收益", ["table_name" => "transaction_data_ys", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                        }
                                        $startMoney = $money;
                                    }
                                    $startRate = $value->rate;
                                }
                            }
                        }

                        $val->handle_state = 2;
                        $val->handle_remark = "已处理";

                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        $val->handle_remark = $e->getMessage();
                    }
                }else{
                    $val->handle_state = 3;
                    $val->handle_remark = "设备或政策不存在";
                }

            } else {
                $val->handle_state = 3;
                $val->handle_remark = "订单无设备信息";
            }
            $val->save();
            sleep(1);
        }
    }

    public function sft()
    {
        $baseUrl = "./trade_log/sft/";
        $fileName = "page.txt";

        if (!file_exists($baseUrl)) {
            mkdir($baseUrl, 0777, true);
        }

        if (!file_exists($baseUrl . $fileName)) {
            $pageInfo = ["page" => 1, "totalPage" => 0, "totalData" => 0];
            file_put_contents($baseUrl . $fileName, json_encode($pageInfo));
        }

        $pageInfo = json_decode(file_get_contents($baseUrl . $fileName), true);

        $list = Transaction::getSftDataList();

        $list = new \ArrayIterator($list);

        if ($list->count() == 0) {
            exit;
        }

        $page = $pageInfo['page'];
        $pageSize = 30;
        $currentPage = $page <= 1 ? 0 : $page - 1;
        $offset = $currentPage * $pageSize;
        $totalPage = ceil($list->count() / $pageSize);

        if ($page == $totalPage || $list->count() < $pageInfo['totalData']) {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        } else {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => $page + 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        }

        $pageData = new LimitIterator($list, $offset, $pageSize);
        foreach ($pageData as $key => $val) {
            $hour = date("H",time());
            if($hour < 4){//每天8点开始上分润
                break;
            }
            if ($val->sn) {
                $sn = $val->sn;

                $equip = Lib::getEquip($sn);
                $policy = Policy::where(["product_id"=>$equip->product_id])->find();

                if($equip && $policy){
                    Db::startTrans();
                    try {
                        $defaultRate = Libs::getEquipRate($sn,"D");
                        if($defaultRate){
                            $level = Tools::getUserLevel($equip->main_id);
                            $profit = Libs::getProfit($policy->id,$equip->product_id,$defaultRate->rate);

//                            $startProfit = 0;
                            foreach ($level as $k => $v) {
                                switch ($k){
                                    case "HX":
                                    case "JG":
                                        $calculateRate = (float)Constant::$profitStep;
                                        break;
                                    default:
                                        $calculateRate = $profit->profit_profit;
                                }

                                $profitMoney = Transaction::roundNumber($val->transaction_amount, $calculateRate);
//                                $diffMoney = $profitMoney - $startProfit;
                                if($profitMoney > 0){
                                    Tools::saveMoney(2, $v, 1, $k, $profitMoney, $sn, $equip->product_id, "分润收益", ["table_name" => "transaction_data_sft", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                }
//                                $startProfit = $profitMoney;
                            }
                        }

                        //调价收益
                        $adjustRate = Libs::getEquipRate($sn,"T");
                        if(count($adjustRate) > 0){
                            $level = Tools::getUserLevel($equip->main_id);
                            if(count($level) > 0) {
                                $policyAdjust = Libs::getPolicyAdjust($policy->id);

                                if (!$policyAdjust) {
                                    throw exception("未设置调价政策");
                                }

                                $policyAdjust = $policyAdjust->toArray();

                                $startRate = $defaultRate->rate;
                                foreach ($adjustRate as $keys => $value){//多次调价进行，每次调价单独进行收益计算
                                    $adjust = ($value->rate - $startRate) * 100;
                                    $changeMoney = Transaction::roundNumber($val->transaction_amount, $adjust);
                                    $startMoney = 0;
                                    foreach ($level as $k => $v) {//各级别角色收益分开计算
                                        $money = bcmul($changeMoney,$policyAdjust[Constant::$levelAlia[$k]] / 100,2);
                                        $finalMoney = $money - $startMoney;
                                        if ($finalMoney > 0) {
                                            Tools::saveMoney(2, $v, 9, $k, $finalMoney, $sn, $equip->product_id, "调价收益", ["table_name" => "transaction_data_sft", "order_num" => $val->order_num, "tran_time" => $val->trading_time]);
                                        }
                                        $startMoney = $money;
                                    }
                                    $startRate = $value->rate;
                                }
                            }
                        }

                        $val->handle_state = 2;
                        $val->handle_remark = "已处理";

                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        $val->handle_remark = $e->getMessage();
                    }
                }else{
                    $val->handle_state = 3;
                    $val->handle_remark = "设备或政策不存在";
                }

            } else {
                $val->handle_state = 3;
                $val->handle_remark = "订单无设备信息";
            }
            $val->save();
            sleep(1);
        }
    }

    //定时任务处理未达标状态
    public function record(){
        $todayStart = strtotime(date("Y-m-d",time()));
        $list = StandardRecord::where(["status" => 0,"end_day" => ["<",$todayStart]])->where("total_money < require_money")->select();
        if(count($list) > 0){
            foreach ($list as $key => $val){
                $val->status = 2;
                $val->trading_time = $val->end_day;
                $val->save();
            }
        }
    }
}
